from decimal import Decimal

from django.shortcuts import render

# Create your views here.

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated

from goods.models import SKU
from orders.serializers import OrderSKUSerializer, OrderSerializer


# GET /orders/settlement
class OrderSettlementView(APIView):
    # 进行认证
    permission_classes = [IsAuthenticated]

    def get(self,request):
        """
        订单详细信息的获取  用户所要结算的商品即为购物车中勾选的商品
        1、从redis购物车中获取用户要结算的商品的sku_id和对应的数量count
        2、根据商品的sku_id获取对应的商品的相关数据&组织运费
        3、将数据序列化返回
        """
        # 获取用户的user
        user = request.user

        # 1、从redis 购物车中获取用户要结算的商品的sku_id和对应的数量count
        # 建立连接
        redis_conn = get_redis_connection('cart')

        # 从redis set元素中获取用户购物车中被勾选的商品id
        cart_selected_key = 'cart_selected_%s' % user.id

        # set中存储的数据Set(b'<sku_id>', b'<sku_id>',....)
        sku_ids = redis_conn.smembers(cart_selected_key)

        # 从redis hash中获取用户购物车中所有的商品id和对应的数量count
        cart_key = 'cart_%s' % user.id
        cart_dict = redis_conn.hgetall(cart_key)

        # 重新组织数据
        cart = {}
        for sku_id, count in cart_dict.items():
            cart[int(sku_id)] = int(count)

        # 2、根据商品sku_id 获取对应的商品数据和组织运费
        # 查询获取处于勾选状态的商品对象
        skus = SKU.objects.filter(id__in=sku_ids)

        # 进行遍历
        for sku in skus:
            # 给sku对象添加相应的count属性值
            sku.count = cart[sku.id]

        # 序列化器进行序列化返回
        serializier = OrderSKUSerializer(skus, many=True)

        # 运费  Decimal 十进制
        freight = Decimal(10.0)

        response_data = {
            'freight': freight,
            'skus': serializier.data
        }
        # 返回响应
        return Response(response_data)


# POST /orders/
class OrdersView(GenericAPIView):
    # 认证
    permission_classes = [IsAuthenticated]
    serializer_class = OrderSerializer

    def post(self, request):
        """
        订单数据保存
        1、获取参数并进行校验（参数的完整性， address的是否存在， pay_method是否合法 此在序列化器中已经默认生成）
        2、保存订单数据
        3、将订单数据序列化并返回
        """
        # 1、获取参数并进行校验
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 2、保存订单数据
        serializer.save()

        # 3、将订单数据序列化并返回
        return Response(serializer.data, status=status.HTTP_201_CREATED)




